package com.ruoyi.framework.aspectj;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Configuration
@Slf4j
public class QueryLogAspect {

    public QueryLogAspect() {
    }

    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
    public void pointGet() {
    }

    @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
    public void pointPost() {
    }

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void pointQuery() {
    }

    // 声明环绕通知
    @Around("pointPost() || pointGet() ")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        Long startTime = System.currentTimeMillis();

        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        log.info("请求uri:{}", request.getRequestURI());
        log.info("请求行参数:{}", request.getQueryString());
        String args = Arrays.toString(pjp.getArgs());
        log.info("请求体参数:{}",args);
        Object ret = null;
        try {
            ret = pjp.proceed();
        }finally {
            Long endTime = System.currentTimeMillis();
            log.info("响应数据耗时{} ms:",endTime-startTime);
        }
        return ret;
    }


}

